<div style="display: none;">
    <textarea name="{{ widget.name }}" {% include "django/forms/widgets/attrs.html" %}>
        {% if widget.value %}{{ widget.value }}{% endif %}
    </textarea>
</div>
<div id="editor—wrapper">
    <div id="toolbar-container"><!-- 工具栏 --></div>
    <div id="editor-container"><!-- 编辑器 --></div>
</div>

<script>
    // 获取cookie
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    const { createEditor, createToolbar } = window.wangEditor

    const content = document.querySelector("#id_{{ widget.name }}")

    const editorConfig = {
        placeholder: 'Type here...',
        onChange(editor) {
            const html = editor.getHtml()
            // 设置表单的值
            content.value = html
            // 也可以同步到 <textarea>
        },
        MENU_CONF: {}
    }

    // 上传图片配置
    editorConfig.MENU_CONF['uploadImage'] = {
        // form-data fieldName ，默认值 'wangeditor-uploaded-image'
        fieldName: 'img',

        // 后端上传图片接口
        server: '{% url "baykeshop:upload" %}',

        // 单个文件的最大体积限制，默认为 2M
        maxFileSize: 2 * 1024 * 1024,

        // 最多可上传几个文件，默认为 100
        maxNumberOfFiles: 10,

        // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
        allowedFileTypes: ['image/*'],

        // csrftoken
        // 自定义增加 http  header
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRFToken': getCookie('csrftoken')
        },

        // 超时时间，默认为 10 秒
        timeout: 30 * 1000, // 5 秒
    }

    const editor = createEditor({
        selector: '#editor-container',
        html: content.value,
        config: editorConfig,
        mode: 'default', // or 'simple'
    })

    const toolbarConfig = {}

    const toolbar = createToolbar({
        editor,
        selector: '#toolbar-container',
        config: toolbarConfig,
        mode: 'default', // or 'simple'
    })
</script>